<?php
/**
 * +--------------------------------------------------------+
 * @Created by Phpstorm.
 * @Category CorsMiddleware.php
 * @Depiction
 * @Author hwy <429208948@qq.com>
 * @Date 2022/3/30  10:00
 * +--------------------------------------------------------+
 */

namespace App\Http\Middleware;


use Closure;
use Illuminate\Http\Response;

class CorsMiddleware
{
    private $headers;
    private $allow_origin;


    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $this->allow_origin = [
            'http://vue.han920.com',
        ];

        $allow_origins = $this->allow_origin[0];
        // 判断请求头中是否包含ORIGIN字段
        if (isset($request->server()['HTTP_ORIGIN'])) {
            $origin = $request->server()['HTTP_ORIGIN'];
            if (in_array($origin, $this->allow_origin)) {
                $allow_origins = $origin;
            }
        }

        $this->headers = [
            'Access-Control-Allow-Origin'  => $allow_origins,
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, authorization, lang ',
            //'Access-Control-Allow-Credentials' => 'true',//允许客户端发送cookie
            'Expires'                      => 'Mon, 26 Jul 1997 05:00:00 GMT',
            'Last-Modified'                => gmdate("D, d M Y H:i:s") . " GMT",
            'Cache-Control'                => 'no-cache, must-revalidate',
            'Pragma'                       => 'no-cache',
        ];

        if ($request->getMethod() == "OPTIONS") {
            $response = new Response('OK', 204);
            foreach ($this->headers as $key => $value) {
                $response->header($key, $value);
            }
            return $response;
        }

        $response = $next($request);
        foreach ($this->headers as $key => $value) {
            $response->header($key, $value);
        }

        return $response;
    }

}
